import { AsyncStorage } from 'react-native';
import Request from "../utils/Request";
import RouterServer from "../utils/RouterServer";
const STORAGE_KEY = "STORAGE_KEY_post";
import { kAuthorization } from "../constant";
const { Actions } = require("react-native-router-flux");
const { Toast } = require('antd-mobile');
export default {
    namespace: 'post',
    state: {
        loading: false,
        list: {
            content: []
        },
        totalPages: 0,
        last: true,
        postType: 'post',
        dynamicItem: null,
    },
    reducers: {
        save(state, { payload }) {
            return Object.assign({}, state, payload);
        }
    },
    effects: {
        *saveToStorage({ payload }, { call }) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload));
        },
        *restoreFromStorage({}, { call, put }) {
            const data = yield call(AsyncStorage.getItem, STORAGE_KEY);
            yield put({
                type: 'save',
                payload: Object.assign({}, JSON.parse(data))
            });
        },
        *fetchData({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            const post = yield select(state => state.post);
            payload['Authorization'] = `${auth.token_type} ${auth.access_token}`;
            yield put({
                type: 'save',
                payload: { loading: true }
            });
            const result = yield call(Request.get, Request.getApi().postList, payload);
            yield put({
                type: 'save',
                payload: { loading: false }
            });
            if (result) {
                if (payload.loadmore) {
                    const content = post.list.content;
                    post.list = result;
                    post.list.content = content.concat(result.content);
                }
                else {
                    post.list = result;
                }
                yield put({
                    type: 'save',
                    payload: Object.assign({}, post)
                });
            }
        },
        *newComment({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            const post = yield select(state => state.post);
            const group = yield select(state => state.group);
            let params = {};
            params['Authorization'] = `${auth.token_type} ${auth.access_token}`;
            params['Content-Type'] = `application/json`;
            params['params'] = { content: payload.message, user: { id: auth.userInfo.id } };
            const data = yield call(Request.post, Request.getApi().newComment, params);
            if (data) {
                params['params'] = data;
                let url = Request.getApi().postComment + `/${payload.id}`;
                if (payload.postType === 'group') {
                    url = Request.getApi().groupPostComment + `/${payload.id}`;
                }
                const result = yield call(Request.put, url, params);
                if (result) {
                    result.comments[result.comments.length - 1].user = auth.userInfo;
                    if (payload.postType === 'group') {
                        const index = group.postList.indexOf(payload.item);
                        if (index !== -1) {
                            group.postList[index] = result;
                        }
                        post.dynamicItem = result;
                        yield put({ type: 'group/save', payload: Object.assign({}, group) });
                        yield put({ type: 'save', payload: Object.assign({}, post) });
                    }
                    else {
                        const index = post.list.content.indexOf(payload.item);
                        if (index !== -1) {
                            post.list.content[index] = result;
                        }
                        post.dynamicItem = result;
                        yield put({ type: 'save', payload: Object.assign({}, post) });
                    }
                }
            }
        },
        *fetchCommentList({ payload }, { call, put, select }) {
        },
        *detail({ payload }, { put, call }) {
            yield put({
                type: 'save',
                payload
            });
            yield call(RouterServer.push, 'postingsDetail');
        },
        *praise({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            const post = yield select(state => state.post);
            const group = yield select(state => state.group);
            let params = {};
            params['Authorization'] = auth.token_type + ' ' + auth.access_token;
            params['Content-Type'] = `application/json`;
            params['params'] = {
                typeId: payload.typeId,
                userId: auth.userInfo.id,
                userName: auth.userInfo.nickName,
                companyName: auth.userInfo.company.name,
                avatar: auth.userInfo.avatar,
            };
            let type = payload.type;
            if (payload.type === 'post') {
                if (payload.from === 'group') {
                    type = 'group_post';
                }
            }
            const praise = yield call(Request.post, Request.getApi().praise + `/${type}`, params);
            if (praise) {
                if (payload.type === 'post') {
                    if (post.dynamicItem) {
                        post.dynamicItem.praise = praise;
                    }
                    if (payload.from === 'group') {
                        const index = group.postList.indexOf(payload.item);
                        const index1 = auth.groupNews.indexOf(payload.item);
                        if (index !== -1) {
                            const postItem = payload.item;
                            postItem.praise = praise;
                            group.postList[index] = postItem;
                        }
                        if (index1 !== -1) {
                            auth.groupNews[index1].praise = praise;
                        }
                    }
                    else {
                        const index = post.list.content.indexOf(payload.item);
                        if (index !== -1) {
                            const postItem = payload.item;
                            postItem.praise = praise;
                            post.list[index] = postItem;
                        }
                    }
                }
                else if (payload.type === 'postcomment') {
                    const index = post.dynamicItem.comments.indexOf(payload.item);
                    if (index !== -1) {
                        const comment = payload.item;
                        comment.praise = praise;
                        post.dynamicItem.comments[index] = comment;
                    }
                }
                yield put({
                    type: 'save',
                    payload: Object.assign({}, post)
                });
                yield put({
                    type: 'group/save',
                    payload: Object.assign({}, group)
                });
                yield put({
                    type: 'auth/save',
                    payload: Object.assign({}, auth)
                });
            }
        },
        *newPost({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            yield put({ type: 'save', payload: { loading: true } });
            let params = {};
            params['Authorization'] = `${auth.token_type} ${auth.access_token}`;
            params['Content-Type'] = `application/json`;
            const file = payload.image;
            let pic = null;
            if (file) {
                const res = yield call(Request.post, Request.getApi().upload + `/${payload.type}`, { file });
                if (res) {
                    pic = Request.checkImageUrl(res.url);
                }
            }
            let p = {
                content: payload.content,
                user: { id: auth.userInfo.id },
                area: { id: auth.userInfo.company.area.id }
            };
            if (pic)
                p['pic'] = pic;
            params['params'] = p;
            let url = Request.getApi().newPost;
            if (payload.type === 'groups') {
                const g = payload.item;
                url = Request.getApi().newGroupPost;
                params['params']['groupId'] = g.id;
            }
            const res1 = yield call(Request.post, url, params);
            yield put({ type: 'save', payload: { loading: false } });
            if (res1) {
                yield call(RouterServer.pop);
            }
        },
        *deletePost({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            const post = yield select(state => state.post);
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            const res = yield call(Request.del, Request.getApi().newPost + `/${payload.post.id}`, payload);
            if (res) {
                yield put({
                    type: 'auth/fetchData',
                    payload: {
                        pi: 1,
                        ps: 5
                    }
                });
                console.log(Actions.currentScene);
                switch (Actions.currentScene) {
                    case '_community':
                        {
                        }
                        break;
                    case 'postingsDetail':
                        {
                            yield call(RouterServer.pop);
                        }
                        break;
                    default:
                        break;
                }
            }
        },
        *deleteComment({ payload }, { call, put, select }) {
            const auth = yield select(state => state.auth);
            const post = yield select(state => state.post);
            let comment = payload.comment;
            delete payload.comment;
            payload[kAuthorization] = auth.token_type + ' ' + auth.access_token;
            console.log(payload);
            const res = yield call(Request.del, Request.getApi().deleteComment + `/${payload.type}`, payload);
            if (res) {
                const index = post.dynamicItem.comments.indexOf(comment);
                if (index !== -1) {
                    post.dynamicItem.comments.splice(index, 1);
                    yield put({
                        type: 'save',
                        payload: Object.assign({}, post)
                    });
                }
            }
        },
    },
    subscriptions: {
        setup({ dispatch }) {
        }
    },
};
